export class WebSocketClient {
  // #socket链接
  private url = '';
  // #socket实例
  private socket: WebSocket | null = null;
  
  constructor(url: string) {
      super();
      this.url = url;
  }
 
  // >消息发送
  public send(message: string): void {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          this.socket.send(message);
      } else {
          console.error('[WebSocket] 未连接');
      }
  }

  // !初始化连接
  public connect(): void {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          return;
      }
      this.socket = new WebSocket(this.url);

      // !websocket连接成功
      this.socket.onopen = event => {
          console.log(`连接成功,等待服务端数据推送[onopen]...`);
      };

      this.socket.onmessage = event => {
      };

      this.socket.onclose = event => {
          console.log(`连接断开[onclose]...`);
      };

      this.socket.onerror = event => {
          console.log(`连接异常[onerror]...`);
      };
  }

  // >关闭连接
  public close(): void {
      if (this.socket) {
          this.socket.close();
          this.socket = null;
      }
  }
}
